package net.p2pcdn.controller;

import com.qc.bean.result.ResponseData;
import net.p2pcdn.captcha.ImageVerificationCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author zx
 */
@RestController
@RequestMapping("common")
public class CaptchaController {
    private final static Logger _logger = LoggerFactory.getLogger(CaptchaController.class);
    private final  static  String CAPTCHA_CODE = "CAPTCHA_CODE";

    @RequestMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*
         1.生成验证码
         2.把验证码上的文本存在session中
         3.把验证码图片发送给客户端
         */
        //用我们的验证码类，生成验证码类对象
        ImageVerificationCode ivc = new ImageVerificationCode();
        BufferedImage image = ivc.getImage();
        //将验证码的文本存在session中
        request.getSession().setAttribute(CAPTCHA_CODE, ivc.getText());
        //将验证码图片响应给客户端
        ImageVerificationCode.output(image, response.getOutputStream());
    }

    @PostMapping("captcha/validate")
    public ResponseData getCaptcha(HttpServletRequest request, String captcha) {
        //将验证码的文本存在session中
        String value =(String) request.getSession().getAttribute(CAPTCHA_CODE);
        if(StringUtils.isNotBlank(value)){
            if(value.equalsIgnoreCase(captcha)){
                return ResponseData.success("ok");
            }else{
                return ResponseData.error("验证码错误",500);
            }
        }else{
            _logger.error("====================no captcha found================================");
            return ResponseData.error("验证码未初始化",500);
        }
    }
}
